package appLoader.data {
	
	import appLoader.data.PropertyTable;
	import appLoader.I_Configuration;
	
	import flash.events.*;
	import flash.events.EventDispatcher;
	
	import appLoader.loaders.LoaderPropertyXML;
	
	import mx.logging.ILogger;
	import mx.logging.Log;
	import mx.logging.LogEventLevel;
	
	/**
	 * Configuration file
	 */
	
	public class BasicConfiguration extends EventDispatcher implements I_Configuration {
		
		static public const ON_CONFIG_DONE:String = 'ON_CONFIG_DONE';
		
		private var _table					:PropertyTable;
		private var _link					:String;
		private var _link2					:String;
		private var _loader					:LoaderPropertyXML;
		private var _debugMode				:Boolean;
		private var _language : String;
		private var _parameterKey : String;
		private var _optional : String;
		private var _isLoaded:Boolean;
		
		private static var logger:ILogger = Log.getLogger("data.BasicConfiguration");
		
		
		public function BasicConfiguration() {
			super();
		}
		
		public function initConfig(link:String, debugLink:String = ''):void {
			this._link = link;
			this._link2 = debugLink;
			this._loader = new LoaderPropertyXML();
			this._loader.addEventListener(Event.COMPLETE, parse);
			this._loader.addEventListener(IOErrorEvent.IO_ERROR, error404);
			this._loader.loads(this._link);
		}
		
		private function error404(e:IOErrorEvent):void {
			if (this._debugMode) {
				if (this._link2 == '') this._link2 = "../" + this._link;
				this._loader.loads(this._link2);
			} else {
				if (this.hasEventListener(IOErrorEvent.IO_ERROR)) this.dispatchEvent(e);
			}
		}
		
		private function parse(evt:Event):void {
			this._table = this._loader.getPropertyTable();
			_isLoaded=true;
			this.dispatchEvent(new Event(ON_CONFIG_DONE));
		}
		
		public function get table():PropertyTable {
			return _table;
		}
		
		public function set table(value:PropertyTable):void {
			_table = value;
		}
		
		public function getXML():XML {
			return XML(this._loader.getData());
		}
		
		override public function toString():String {
			var s:String = "[ Config ]\n";
			var tt:int = this._table.length();
			while (tt--) s += ". " + this._table.getKeyByIndex(tt) + " -> " + this._table.getValueByIndex(tt) + "\n";
			s += ". link: " + this._link;
			return s;
		}
		
		public function get language():String
		{
			return _language;
		}
		
		public function set language(value:String):void
		{
			_language = value;
		}
		
		public function get parameterKey():String
		{
			return _parameterKey;
		}
		
		public function set parameterKey(value:String):void
		{
			_parameterKey = value;
		}
		
		public function isLoaded():Boolean{
			return _isLoaded;
		}

		public function get link():String
		{
			return _link;
		}

		public function set link(value:String):void
		{
			_link = value;
		}

		public function get optional():String
		{
			return _optional;
		}

		public function set optional(value:String):void
		{
			_optional = value;
		}


	}
	
}
